package com.raising.modules.sys.controller;

import com.google.common.collect.Lists;
import com.raising.StaticParam;
import com.raising.framework.controller.BaseController;
import com.raising.framework.entity.ResultCode;
import com.raising.framework.entity.ResultVo;
import com.raising.framework.interceptor.Page;
import com.raising.modules.sys.entity.Organization;
import com.raising.modules.sys.service.OrganizationService;
import com.raising.modules.sys.utils.DictUtils;
import com.raising.modules.sys.utils.OrgUtils;
import com.raising.modules.sys.utils.SysConfigUtil;
import com.raising.utils.ExceptionsUtils;
import com.raising.utils.JStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * 组织机构控制器
 * 单位管理
 * @author gaoy
 */
@Controller
@RequestMapping("${adminPath}/organization")
public class OrganizationController extends BaseController {

	@Autowired
	private OrganizationService organizationService;

    /**
     * 单位列表页
	 * @author gaoyuan
     * @return
     */
    @RequiresPermissions("sys:organization:view")
    @RequestMapping()
    public String list() {
		olog("进入单位管理页面");
		return "sys/organization/list";
    }

    /**
     * 加载权限内单位数据
     * @author GaoYuan
     * @datetime 2018/1/24 下午5:31
     */
	@RequiresPermissions("sys:organization:view")
	@RequestMapping(value = "/getMyOrgList.json", method = RequestMethod.GET)
	public @ResponseBody ResultVo getMyOrgList() {
		return ResultVo.success().data(OrgUtils.getMyOrgList());
	}

	/**
	 * 获取当前权限内的数据
	 * @author GaoYuan
	 * @datetime 2018/1/24 下午5:31
	 */
	@RequiresPermissions("sys:organization:view")
	@RequestMapping(value = "/getPage.json", method = RequestMethod.POST)
	public @ResponseBody ResultVo getPage(Organization organization, Page<Organization> page) throws Exception{
		if(!OrgUtils.isMyOrg(organization.getId()) || JStringUtils.isBlank(organization.getId())){
			organization.setId(OrgUtils.getMyOrgId());
		}
		page.setEntity(organization);
		return ResultVo.success().data(organizationService.getPage(page));
	}

	/**
     * 跳转到新增页
     * @param model
     * @return
     */
    @RequiresPermissions("sys:organization:edit")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
     	// 是否可用
        model.addAttribute("yn", DictUtils.getDictList("DIM_YN"));
        return "sys/organization/add";
    }

	/**
	 * 执行新增
	 * @author gaoyuan
	 * @param organization
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:organization:edit")
	@RequestMapping(value = "/insertOrg.json", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo insertOrg(Organization organization, Model model) throws Exception{
		if(organization == null
				|| JStringUtils.hasBlank(
						organization.getParentId(),
						organization.getName(),
						organization.getShortName()
					)
		){
			return ResultVo.failure(ResultCode.PARAM_EMPTY).desc("参数不合法");
		}

		if(!OrgUtils.isMyOrg(organization.getParentId()) ){
			return ResultVo.failure(ResultCode.NO_PERMISSIONS).desc("没有权限设置").data(organization.getId());
		}

		//根据单位标识id查询机构当前下属单位最大的编号no
		String maxNo = organizationService.getSubMaxNoById(organization.getParentId());
		if(JStringUtils.isBlank(maxNo)){
			Organization parent = organizationService.get(organization.getParentId());
			organization.setNo(parent.getNo() + "01");
		}else{
			organization.setNo(String.valueOf(Long.parseLong(maxNo) + 1));
		}

		ResultVo resultVo = organizationService.insert(organization);
		olog("新增单位【"+organization.getName()+"】","{id:"+organization.getId()+"}");
		return resultVo;
	}

	/**
	 * 跳转到修改页
	 * @param id
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:organization:edit")
	@RequestMapping(value = "/update", method = RequestMethod.GET)
	public String update(String id, Model model) throws Exception{
		Organization organization = organizationService.get(id);
		model.addAttribute("organization", organization);
		// 是否可用
        model.addAttribute("yn",DictUtils.getDictList("DIM_YN"));
		return "sys/organization/edit";
	}

	/**
	 * 执行修改
	 * @author gaoyuan
	 * @param organization
	 * @return
	 */
	@RequiresPermissions("sys:organization:edit")
	@RequestMapping(value = "/updateOrg.json", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo updateOrg(Organization organization) throws Exception{
		if(organization == null || JStringUtils.hasBlank(
				organization.getParentId(),
				organization.getName(),
				organization.getShortName())) {
			return ResultVo.failure(ResultCode.PARAM_EMPTY).desc("参数不合法");
		}
		Organization old = organizationService.get(organization.getId());

		//判断层级有没有变化
		if(JStringUtils.isBlank(old.getNo()) || !old.getParentId().equals(organization.getParentId())){
			//根据单位标识id查询机构当前下属单位最大的编号no
			String maxNo = organizationService.getSubMaxNoById(organization.getParentId());
			if(JStringUtils.isBlank(maxNo)){
				Organization parent = organizationService.get(organization.getParentId());
				organization.setNo(parent.getNo() + "01");
			}else{
				organization.setNo(String.valueOf(Integer.parseInt(maxNo) + 1));
			}
		}else{
			organization.setNo(old.getNo());
		}
		organizationService.update(organization);
		olog("修改单位【"+old.getName()+"】","{id:"+organization.getId()+"}");
		return ResultVo.success().desc("编辑成功").data(organization.getParentId());
	}

	/**
	 * 执行数据上下级清洗操作
	 * @author gaoyuan
	 * @param organization
	 * @return
	 */
	@RequiresPermissions("sys:organization:edit")
	@RequestMapping(value = "/updateTree.json", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo updateTree(Organization organization) {
		organizationService.updateTree();
		return ResultVo.success().desc("成功整理单位层级数据").data(organization.getParentId());
	}

	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequiresPermissions("sys:organization:delete")
	@RequestMapping(value = "/delete.json", method = RequestMethod.POST)
	public @ResponseBody ResultVo delete(String id) throws Exception{
		String rootNode = "1";
		if(rootNode.equals(id)){
			return ResultVo.failure(ResultCode.NO_PERMISSIONS).desc("超级管理员才能删除");
		}else{
			Organization organization = new Organization();
			//删除前判断是否存在下级节点
			organization.setStatus(StaticParam.VALID_STRING);
			int count = organizationService.findNext(id);
			if(count>0){
				return ResultVo.failure(ResultCode.NO_PERMISSIONS).desc("删除失败，存在子节点，请先删除子节点");
			}else{
				ResultVo resultVo = organizationService.delete(id);
				olog("删除单位","{id:"+id+"}");
				return resultVo;
			}
		}
	}


	/**
	 * 管理员 更新指定单位头像 org/id.png
	 * @author GaoYuan
	 * @datetime 2018/1/27 下午5:04
	 */
	@RequestMapping(value = "/uploadHeadImg", method = RequestMethod.POST)
	public @ResponseBody String uploadHeadImg(@RequestParam("file") MultipartFile[] files, String orgId) {
		List<String> list = Lists.newArrayList();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
//				list = saveFile(request, file, list);
				// 判断文件是否为空
				if (!file.isEmpty()) {
					try {
						// 保存的文件路径(如果用的是Tomcat服务器，文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中)
						String savePathPre = SysConfigUtil.getConfigValueByKey("UPLOAD_SAVE_PATH_IMG","");
						String readPath = "/org/"+orgId+".png";
						String filePath = savePathPre + readPath;

						File saveDir = new File(filePath);
						File oldFile = new File(filePath);
						if (!saveDir.getParentFile().exists()){
							saveDir.getParentFile().mkdirs();
						}
						if(oldFile.exists()){
							oldFile.delete();
						}
						// 转存文件
						file.transferTo(saveDir);
						list.add(readPath);

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

			if(list.size()>0){
				Organization organization = new Organization();
				organization.setId(orgId);
				organization.setPhoto(list.get(0));
				organizationService.updateHeadImg(organization);
				olog("更新单位照片","{id:"+orgId+"}");
			}
		}
		//返回数据
		return "<script>parent.loadHeadImg('"+list.get(0)+"');</script>";
	}


}
